<?php
/**
 * 特殊独立奖池
 */
namespace App\Models\MainDB;

use App\Services\Tools\HelperService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class IndependentPool extends Model{

    protected $table = 'ln_independent_pool';     //数据库内完整表名

    protected $primaryKey = 'id';    //主键名

    protected $fillable = [
        'id',      //主键ID
        'gift_id',         //礼物id
        'number',         //数量榉木
        'type',         //奖池类型
    ];

    public $timestamps = false;

    //获取列表
    public function getIndependentPoolList($type = 1) {
        $list = $this->from('ln_independent_pool as a')
            ->select('a.id', 'a.gift_id', 'a.number', 'b.name as gift_name', 'b.price', 'b.picture', 'b.special','a.critical_times')
            ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
            ->where(['a.type' => $type])
            ->orderBy('b.price', 'desc')
            ->get();
        foreach ($list as &$value) {
            $value['quality'] = HelperService::giftRank($value['price']);
        }
        return $list;
    }

    //获取剩余次数
    public function getIndependentPoolCount($type = 1) {
        $total = $this->where(['type' => $type])->sum('number');
        return $total ?: 0;
    }

    //获取剩余总金额
    public function getIndependentPoolTotal($type = 1) {
        $total = $this->from('ln_independent_pool as a')
            ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
            ->where(['a.type' => $type])
            ->sum(DB::raw('a.number * b.price'));
        return $total ?: 0;
    }

    //获取所有礼物
    public function getAllGift($type = 1) {
        return $this->from('a')
            ->select('a.id', 'a.gift_id', 'a.number', 'b.name as gift_name', 'b.price', 'b.picture', 'b.special')
            ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
            ->where(['a.type' => $type])
            ->get()->toArray();
    }

    //礼物是否存在
    public function giftIsExist($type, $giftId, $id = 0)
    {
        return $this->where('type', $type)
            ->where('gift_id', $giftId)
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })
            ->value('id');
    }
}